import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';

declare var $: any;
@Component({
	selector: 'sa-device-control',
	templateUrl: './device-control.component.html',
})
export class DeviceControlComponent implements OnInit {

	validatorOptions = {
		excluded: [":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			//			deviceId:{
			//				trigger:"change",
			//				validators: {
			//					notEmpty: {
			//						message: '请选择车牌号码'
			//					}
			//				}
			//			}
		}
	}
	tableData: any[] = []; //table数据
	totalCount: number = 0; //分页总条数
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	tableSearch: any = {
		searchKey: ''
	}
	startTime: string = '';
	endTime: string = '';
	deviceControlFrom: any = {
		id: null,
		deviceId: '',
		carNumber: '',
		limitStartTime: '',
		limitEndTime: '',
		limitType: '1'
	}
	formType: string = 'new';
	deviceId: string = '';
	carNumber: string = '';
	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage || 1;
		});
	}
	//擦除用户所选值
	delCarNumberSelect2() {
		this.deviceId = '';
		this.carNumber = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str = $("<span class='select2-selection__placeholder'>请选择</span>");
		$('#carNumberSelect2').val("");
		$("#select2-carNumberSelect2-container").empty();
		$("#select2-carNumberSelect2-container").attr("title", "");
		$("#select2-carNumberSelect2-container").prepend(str);
		this.load();
	}
	//擦除用户所选值
	delCarNumberSelect2From() {
		this.deviceControlFrom.deviceId = '';
		this.deviceControlFrom.carNumber = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str = $("<span class='select2-selection__placeholder'>请选择</span>");
		$('#carNumberSelect2From').val("");
		$("#select2-carNumberSelect2From-container").empty();
		$("#select2-carNumberSelect2From-container").attr("title", "");
		$("#select2-carNumberSelect2From-container").prepend(str);
	}
	// 接收子组件传递过来的数据 
	getSelectTableTime(time) {
		this.startTime = time.startTime;
		this.endTime = time.endTime;
	}
	//初始化日期
	initDate() {
		System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
			() => {
				System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
					$("#limitStartTime").datetimepicker({//时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true,
					}).on("changeDate", function (e) {
						var date = e.date;
						if (!date) { return; }
						var time = common.getTimeMmss(date);
						$("#limitEndTime").datetimepicker("setStartDate", time);
					});
					$("#limitEndTime").datetimepicker({//时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true,
					}).on("changeDate", function (e) {
						var date = e.date;
						if (!date) { return; }
						var time = common.getTimeMmss(date);
						$("#limitStartTime").datetimepicker("setEndDate", time);
					});
				});
			});
	}
	//车辆
	initCarSelect2(id) {
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				var that = this;
				$("#" + id).select2({
					language: "zh-CN",
					minimumInputLength: 2,
					allowClear: true,
					placeholder: "请选择",
					ajax: {
						url: config.BaseURL + "stats/carListByCarNumber.html",
						dataType: 'json',
						delay: 50,
						method: "POST",
						xhrFields: { withCredentials: true },
						data: function (params) {
							return { "carNumber": params.term };
						},
						processResults: function (data, params) {
							var options = new Array();
							// 小于10个数量才判断重复
							if (data.data.length <= 10) {
								let arr = []
								let sameCar = []
								// 判断相同的车牌号
								for (let index = 0; index < data.data.length; index++) {
									let car = data.data[index];
									if (arr.indexOf(car.carNumber) != -1) {
										sameCar.push(car.carNumber)
									} else {
										arr.push(car.carNumber);
									}
								}
								$(data.data).each(function (index, car) {
									if (sameCar.indexOf(car.carNumber) != -1) {
										options.push({
											id: car.deviceId,
											text: car.carNumber + "[" + car.parentName + "]"
										})
									} else {
										options.push({
											id: car.deviceId,
											text: car.carNumber
										})
									}
								});
							} else {
								$(data.data).each(function (index, car) {
									options.push({
										id: car.deviceId,
										text: car.carNumber
									})
								});
							}
							return {
								results: options //获取查询后的结果
							};
						},
						cache: true
					},
					templateResult: function (state) {
						if (!state.id) { return state.text; }
						var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
						return $state;
					},
				}).on("select2:select", function (e) {
					var data = e.params.data;
					if (id == 'carNumberSelect2') {
						that.deviceId = data.id;
						if (data.text.indexOf('[') > 0) {
							that.carNumber = data.text.split('[')[0];
						} else {
							that.carNumber = data.text;
						}
						// that.carNumber = data.text;
					}
					if (id == 'carNumberSelect2From') {
						that.deviceControlFrom.deviceId = data.id;
						if (data.text.indexOf('[') > 0) {
							that.deviceControlFrom.carNumber = data.text.split('[')[0];
						} else {
							that.deviceControlFrom.carNumber = data.text;
						}
						// that.deviceControlFrom.carNumber = data.text;
						$("#deviceIdFrom").val(that.deviceControlFrom.deviceId).change();
					}
				});
			})
		})
	}
	ngOnInit() {
		this.initCarSelect2('carNumberSelect2');
		this.initCarSelect2('carNumberSelect2From');
		this.load();
		this.initDate();
	}
	//table刷新
	refresh() {
		this.load();
	}
	//表格搜索
	table_search() {
		this.curPage = 1;
		this.load();
	}
	//初始化加载list数据
	load() {
		let timeCheck = common.correctTimeParams(this.startTime, this.endTime, 0);
		if (!timeCheck.status) {
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		let data = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
				deviceId: this.deviceId,
				startTime: this.startTime,
				endTime: this.endTime,
				searchKey: common.stringTrim(this.tableSearch.searchKey)
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(data);
		this.jsonApiService.http("carDataLimit/queryLimitConfigList.html", reqdata).subscribe(data => {
			if (data.isSuccess) {
				this.tableData = data.exhibitDatas;
				this.totalCount = data.recordCount;
			} else {
				this.jsonApiService.message(data.message);
			}
		})
	}
	//删除
	delRow(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			this.jsonApiService.http_obj("carDataLimit/deleteLimitConfig.html", { id: row.id }).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
				}
			})
		})
	}

	//分页回调
	paginate(e) {
		this.curPage = e.page + 1;
		this.pageSize = e.rows;
		this.load();
	}
	/*
	 * 新增
	 */
	table_add(modal) {
		this.modalClose(modal);
		modal.show();
		this.formType = 'new';
	}
	/*
	 * 编辑
	 */
	editRow(row, modal) {
		modal.show();
		this.deviceControlFrom.id = row.id;
		this.formType = 'updata';
		this.jsonApiService.http_obj("carDataLimit/queryLimitConfigById.html", { id: row.id }).subscribe(data => {
			if (data.data) {
				for (let item in this.deviceControlFrom) {
					this.deviceControlFrom[item] = data.data[item];
					if (item == 'limitType') {
						this.deviceControlFrom[item] = data.data[item] + '';
					}
				}
			}
		})
	}
	limitTypeChange(val) {
		this.deviceControlFrom.limitType = val;
	}
	/*
	 * 关闭弹窗
	 */
	modalClose(modal) {
		modal.hide();
		$("#deviceControlFrom").data('bootstrapValidator').resetForm();
		this.deviceControlFrom.id = '';
		this.deviceControlFrom.deviceId = '';
		this.deviceControlFrom.carNumber = '';
		this.deviceControlFrom.limitStartTime = '';
		this.deviceControlFrom.limitEndTime = '';
		this.deviceControlFrom.limitType = '1';
		$('#limitStartTime').val('');
		$('#limitEndTime').val('');
		$('#carNumberSelect2From').val('').trigger('change');
		$("#limitEndTime").datetimepicker("setStartDate", null);
		$("#limitStartTime").datetimepicker("setEndDate", null);
	}
	/*
	 * form提交
	 */
	deviceControlSubmit(modal) {
		this.deviceControlFrom.limitStartTime = $('#limitStartTime').val();
		this.deviceControlFrom.limitEndTime = $('#limitEndTime').val();
		//		$('#deviceControlFrom').bootstrapValidator('validate'); //开启验证
		//		let isValid = $('#deviceControlFrom').data('bootstrapValidator').isValid();  //验证是否通过
		let timeCheck = common.correctTimeParams(this.deviceControlFrom.limitStartTime, this.deviceControlFrom.limitEndTime, 0);
		if (!timeCheck.status) {
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		if (!this.deviceControlFrom.deviceId && this.formType == 'new') {
			this.jsonApiService.message('请选择车牌号码');
			return;
		}
		//		if(isValid){
		let url;
		if (this.formType == 'new') {
			url = "carDataLimit/addLimitConfig.html";
		} else if (this.formType == 'updata') {
			url = "carDataLimit/updateLimitConfig.html";
		}
		this.jsonApiService.http_obj(url, this.deviceControlFrom).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.load();
				this.modalClose(modal);
			}
		})
		//		}
	}

}